package com.user.controller;


import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.user.pojo.User;
import com.user.service.UserService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.*;

@RestController
@RequestMapping("/api/users")
@Slf4j
public class UserController {

    @Autowired
    private UserService userService;

    /**
     * 获取用户列表
     * @param pageNum
     * @param pageSize
     * @param keyword
     * @return
     */
    @GetMapping
    public ResponseEntity<IPage<User>> list(
            @RequestParam(defaultValue = "1") Integer pageNum,
            @RequestParam(defaultValue = "10") Integer pageSize,
            @RequestParam(required = false) String keyword) {

        Page<User> page = new Page<>(pageNum, pageSize);
        IPage<User> result = userService.listUsers(page, keyword);
        return ResponseEntity.ok(result);
    }
    /**
     * 获取用户详情
     * @param id
     * @return
     */
    @GetMapping("/{id}")
    public ResponseEntity<User> getById(@PathVariable Long id) {
        log.info("获取用户详情：{}", id);
        User user = userService.getById(id);
        return user != null ? ResponseEntity.ok(user) : ResponseEntity.notFound().build();
    }
    /**
     * 新增用户
     * @param user
     * @return
     */
    @PostMapping
    public ResponseEntity<String> save(@RequestBody User user) {
        user.setPassword("123456"); // 默认密码，实际应加密
        boolean saved = userService.save(user);
        return saved ? ResponseEntity.ok("新增成功") : ResponseEntity.badRequest().body("失败");
    }
    /**
     * 修改用户
     * @param user
     * @return
     */
    @PutMapping
    public ResponseEntity<String> update(@RequestBody User user) {
        boolean updated = userService.updateById(user);
        return updated ? ResponseEntity.ok("更新成功") : ResponseEntity.badRequest().body("失败");
    }
    /**
     * 删除用户
     * @param id
     * @return
     */
    @DeleteMapping("/{id}")
    public ResponseEntity<String> delete(@PathVariable Long id) {
        boolean removed = userService.removeById(id);
        return removed ? ResponseEntity.ok("删除成功") : ResponseEntity.notFound().build();
    }
}